<?php
namespace App\Http\Middleware;

use Closure;
use Zizaco\Entrust\EntrustFacade as Entrust;
use Route, URL, Auth;
use App\Models\Templates;
use Log;
class AuthenticateAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param  string|null $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        //return $next($request);
		if(!$request->session()->has('authAdminCondition')||!$request->session()->has('authAdminUserCondition')){
			$uid = auth()->user()->id;
			$condition = [['uid', '>', 0],];
			$conditionUser = [['id', '>', 0],];
			if($uid > 1){
				$condition = array('uid'=>$uid);
				$conditionUser = array('id'=>$uid);
			}
			$template = Templates::where('uid',auth()->user()->id)->first();
			if($template === NULL){
				$templateUser = Templates::find(1);
				$newDataTmp['uid'] = auth()->user()->id;
				$newDataTmp['username']= auth()->user()->name;
				$newDataTmp['name'] = $templateUser->name;
				$newDataTmp['mark'] = $templateUser->mark;
				$newDataTmp['source_code'] = $templateUser->source_code;
				Templates::insert($newDataTmp);
			}
			$request->session()->put('authAdminCondition',$condition);
			$request->session()->put('authAdminUserCondition',$conditionUser);
		}
        if (Auth::guard('admin')->user()->id === 1) {
            return $next($request);
        }

        $previousUrl = URL::previous();
         if (!Auth::guard('admin')->user()->can(Route::currentRouteName())) {
            if ($request->ajax() && ($request->getMethod() != 'GET')) {
                return response()->json([
                    'status' => -1,
                    'code' => 403,
                    'msg' => '您没有权限执行此操作'
                ]);
            } else {
                return response()->view('admin.errors.403', compact('previousUrl'));
            }
        } 

        return $next($request);
    }
}
